package org.gnomus.data;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class group extends object {

    public group(Entity e) {
        super(e);
        setName((String) e.getProperty("name"));
    }

    public group(String name) {
        super("group");
        setName(name);
    }

    public static List<group> fetch(Key ak) {
        List<group> groups = new ArrayList<group>();
        for (link lnk : link.fetch("account", ak, "group", null)) {
            Entity e = store.get(lnk.getTargetKey());
            if (e == null) { continue; }
            groups.add(new group(e));
        }
        return groups;
    }

    public void setName(String name) {
        put("name", name);
    }

    public String getName() {
        return (String) get("name");
    }

    public void updateMembers(List<Map> members) {
        for (Map m : members) {
            if (m.containsKey("id")) {
                Entity e = store.get("member", (String) m.get("id"));
                e.setProperty("first_name", m.get("first_name"));
                e.setProperty("last_name", m.get("last_name"));
                e.setProperty("active", m.get("active"));
                store.put(e);
            } else {
                member mbr = new member((String) m.get("first_name"), (String) m.get("last_name"));
                mbr.save();
                link lnk = new link(this.kind, this.key, mbr.kind, mbr.key);
                lnk.save();
            }
        }
    }

    public List<member> getMembers() {
        return member.fetch(this.key);
    }

    public void setAssignments(String assignments) {
        put("assignments", assignments);
    }

    public List<assignment> getAssignments() {
        return assignment.fetch(this.key);
    }
}
